﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.WebSockets;
using Newtonsoft.Json;

namespace appSocket
{
    /// <summary>
    /// Message 的摘要说明
    /// </summary>
    public class Message : IHttpHandler
    {
        public static readonly string wsCode = ConfigurationManager.AppSettings["wsCode"].ToString();
        private static Dictionary<string, WebSocket> CONNECT_POOL = new Dictionary<string, WebSocket>();//用户连接池
        private static Dictionary<string, List<MessageInfo>> MESSAGE_POOL = new Dictionary<string, List<MessageInfo>>();//离线消息池
        public void ProcessRequest(HttpContext context)
        {
            if (context.IsWebSocketRequest)
            {
                context.AcceptWebSocketRequest(ProcessChat);
            }
        }

        private async Task ProcessChat(AspNetWebSocketContext context)
        {
            WebSocket socket = context.WebSocket;
            string user = context.QueryString["user"].ToString();
            string code = context.QueryString["code"].ToString();

            SaveLog( string.Format("0调用:{0},{1}|{2}", user, code, wsCode));
            if (wsCode != code) {
                return;
            }
            try
            {
                #region 用户添加连接池
                //第一次open时，添加到连接池中
                if (!CONNECT_POOL.ContainsKey(user))
                {

                    SaveLog(string.Format("1添加用户线程:{0},{1}|{2}", user, code, wsCode));
                    CONNECT_POOL.Add(user, socket);//不存在，添加
                }
                else
                {

                    if (socket != CONNECT_POOL[user])//当前对象不一致，更新
                    {
                        SaveLog(string.Format("2用户线程:{0},{1}|{2}", user, code, wsCode));
                        CONNECT_POOL[user] = socket;
                    }
                }
                #endregion
                #region 离线消息处理
                if (MESSAGE_POOL.ContainsKey(user))
                {
                    SaveLog(string.Format("3离线消息处理:{0},{1}|{2}", user, code, wsCode));
                    List<MessageInfo> msgs = MESSAGE_POOL[user];
                    foreach (MessageInfo item in msgs)
                    {
                        await socket.SendAsync(item.MsgContent, WebSocketMessageType.Text, true, CancellationToken.None);
                    }
                    MESSAGE_POOL.Remove(user);//移除离线消息
                }
                #endregion

                string descUser = string.Empty;//目的用户
                while (true)
                {
                    if (socket.State == WebSocketState.Open)
                    {
                        ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024 * 500]);
                        WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);

                        SaveLog(string.Format("4消息处理:{0},{1}|{2}", user, code, wsCode));
                        #region 消息处理（字符截取、消息转发）
                        try
                        {
                            #region 关闭Socket处理，删除连接池
                            if (socket.State != WebSocketState.Open)//连接关闭
                            {
                                SaveLog(string.Format("-----连接关闭:{0}", "1"));
                                if (CONNECT_POOL.ContainsKey(user)) CONNECT_POOL.Remove(user);//删除连接池
                                break;
                            }
                            #endregion


                            string userMsg = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);//发送过来的消息
                            SaveLog(string.Format("-----发送过来的消息:{0}", userMsg));
                            var info = JsonConvert.DeserializeObject<Dictionary<string, object>>(userMsg);
                            string userid = GetKey(info, "user");
                            SaveLog(string.Format("-----目标客户:{0},{1}|", userid, GetKey(info, "msg")));
                            buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(GetKey(info, "msg")));

                            if (userid != "WSALL")
                            {
                                descUser = userid;
                            }
                            if (CONNECT_POOL.ContainsKey(descUser))//判断客户端是否在线
                            {

                                SaveLog(string.Format("5客户端是否在线:{0},{1}|{2}", user, code, wsCode));
                                WebSocket destSocket = CONNECT_POOL[descUser];//目的客户端
                                if (destSocket != null && destSocket.State == WebSocketState.Open)
                                {
                                    await destSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                                }
                            }
                            else
                            {
                                SaveLog(string.Format("6客户端不在线:{0},{1}|{2}", user, code, wsCode));
                                await Task.Run(() =>
                                 {
                                     if (!MESSAGE_POOL.ContainsKey(descUser))//将用户添加至离线消息池中
                                    {
                                         MESSAGE_POOL.Add(descUser, new List<MessageInfo>());
                                     }
                                     MESSAGE_POOL[descUser].Add(new MessageInfo(DateTime.Now, buffer));//添加离线消息
                                });
                            }
                        }
                        catch (Exception x)
                        {
                            SaveLog(string.Format("执行错误:{0}",  x.Message.ToString()));
                        }
                        #endregion
                    }
                    else
                    {
                        break;
                    }
                }//while end
            }
            catch (Exception x)
            {
                //整体异常处理
                if (CONNECT_POOL.ContainsKey(user)) 
                {
                    CONNECT_POOL.Remove(user);
                }

                SaveLog(string.Format("执行错误:{0}",  x.Message.ToString()));
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public static void SaveLog(string errorMsg, string path="log/test.txt")
        {
            errorMsg = errorMsg.Replace("{#url#}", HttpContext.Current.Request.Url.ToString());
            errorMsg = errorMsg.Replace("{#sysdate#}", DateTime.Now.ToString());
            string filename = HttpContext.Current.Server.MapPath(path);
            string filepath = filename.Substring(0, filename.LastIndexOf("\\") + 1);
            if (!System.IO.Directory.Exists(filepath))
            {
                System.IO.Directory.CreateDirectory(filepath);
            }
            if (!File.Exists(filename))
            {
                FileStream file = File.Create(filename);
                file.Dispose();
            }
            try
            {
                System.IO.StreamWriter sw = new System.IO.StreamWriter(filename, true, System.Text.Encoding.GetEncoding("utf-8"));
                sw.WriteLine("时间：" + DateTime.Now.ToString() + "---页面"+ HttpContext.Current.Request.Url.ToString()+"------");
                sw.WriteLine("        ----------------------------------");
                sw.WriteLine("        "+errorMsg); 
                sw.WriteLine("        ----------------------------------");
                sw.Close();
            }
            catch { }
        }
        public string GetKey(Dictionary<string, object> dic, string key)
        {
            var result = key == "id" ? "-1" : "";
            if (dic.Keys.Contains(key))
            {
                result = dic[key] == null ? "" : dic[key].ToString();
            }
            return result;
        }
    }

    /// <summary>
    /// 离线消息
    /// </summary>
    public class MessageInfo
    {
        public MessageInfo(DateTime _MsgTime, ArraySegment<byte> _MsgContent)
        {
            MsgTime = _MsgTime;
            MsgContent = _MsgContent;
        }
        public DateTime MsgTime { get; set; }
        public ArraySegment<byte> MsgContent { get; set; }
    }

   
}